<?php
//----------------------------------------------------
//Javascript側から送られたデータを使用可能にする
//----------------------------------------------------
$data        = array();

$db_table    = htmlspecialchars($_GET['db_table'],    ENT_QUOTES);
$q_word      = htmlspecialchars($_GET['q_word'],      ENT_QUOTES);
$page_num    = htmlspecialchars($_GET['page_num'],    ENT_QUOTES);
$per_page    = htmlspecialchars($_GET['per_page'],    ENT_QUOTES);
$field       = htmlspecialchars($_GET['field'],       ENT_QUOTES);
$show_field  = htmlspecialchars($_GET['show_field'],  ENT_QUOTES);
$hide_field  = htmlspecialchars($_GET['hide_field'],  ENT_QUOTES);
$select_field= htmlspecialchars($_GET['select_field'],ENT_QUOTES);
$order_field = htmlspecialchars($_GET['order_field'], ENT_QUOTES);
$primary_key = htmlspecialchars($_GET['primary_key'], ENT_QUOTES);
$order_by    = htmlspecialchars($_GET['order_by'],    ENT_QUOTES);

$offset      = ($page_num - 1) * $per_page;
$show_field  = ($show_field)
	? explode(',',$show_field)
	: array(false);
$hide_field  = explode(',',$hide_field);


//----------------------------------------------------
//DBへ接続
//----------------------------------------------------
$db = sqlite_open('../SQLite2/test.sqlite','0600');


//----------------------------------------------------
//候補を取得
//----------------------------------------------------
$query = "

	SELECT   $select_field
	FROM     $db_table
	WHERE    $field LIKE '%$q_word%'
	ORDER BY (
	             CASE
	                 WHEN $order_field LIKE '$q_word%'
	                 THEN 0
	                 ELSE 1
	             END
	         ),$order_field $order_by
	LIMIT    $per_page
	OFFSET   $offset

";
$rows  = sqlite_query($db,$query);

$attached_cnt = 0;
while ($row = sqlite_fetch_array($rows,SQLITE_ASSOC))
{
	$data['cnt_page'] ++;
	foreach($row as $key => $value){

		//"セレクト専用"のオプションで使用
		if($key == $primary_key){
			$data['primary_key'][] = $value;
		}

		//候補リスト用の値を取得
		if($key == $field){
			$data['candidate'][] = $value;

		} else {

			//サブ情報で使用
			if(!in_array($key, $hide_field)){

				//除外カラムには該当しないけど、表示カラムにも該当しない場合は非表示。
				//ただし、表示カラムに『*』がある場合は非表示とはならない。
				if(
					$show_field[0] !== false
					&& !in_array('*', $show_field)
					&& !in_array($key, $show_field)
				){
					continue;
				}

				$data['attached'][$attached_cnt][] = array(
					0 => $key,
					1 => $value
				);
			}
		}
	}
	$attached_cnt++;
}


//----------------------------------------------------
//全候補数を取得
//----------------------------------------------------
$query = "
	SELECT   $field
	FROM     $db_table
	WHERE    $field LIKE '%$q_word%'
";
$data['cnt'] = sqlite_num_rows( sqlite_query($db,$query) );

echo json_encode($data);


//----------------------------------------------------
//終了
//----------------------------------------------------
//DBとの通信を切断
sqlite_close($db);

?>